﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include    <QPainter>
#include"globe.h"


void MainWindow::addPageToTab(int index, QString name, int bps)
{
    QFormFunction *FomFun = new QFormFunction(this);
    FomFun->setAttribute(Qt::WA_DeleteOnClose); //关闭时候销毁

    QString curName = "通道 "+name;
    int cur = ui->tabWidget->addTab(FomFun,curName);
    FomFun->getMessage(index,name,bps);
    ui->tabWidget->setCurrentIndex(cur);
    ui->tabWidget->setVisible(true);
    //
}

void MainWindow::paintEvent(QPaintEvent *event)
{
    //绘制窗口背景图片
    Q_UNUSED(event);
    QPainter painter(this);
    painter.drawPixmap(0,ui->mainToolBar->height(),this->width(),
                        this->height()-ui->mainToolBar->height()-ui->statusBar->height(),
                       QPixmap(":/images/images/back2.jpg"));
}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->tabWidget->setVisible(false);
    ui->tabWidget->clear();//清除所有页面
    ui->tabWidget->tabsClosable(); //Page有关闭按钮，可被关闭

    this->setCentralWidget(ui->tabWidget); //设置为中心
    this->setWindowState(Qt::WindowMaximized);//设置窗口最大化
    this->setAutoFillBackground(true);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_actCAN_Open_triggered()
{
    QDialogCAN *dlgCAN = new QDialogCAN(this);
    Qt::WindowFlags flags = dlgCAN->windowFlags();
    dlgCAN->setWindowFlags(flags|Qt::MSWindowsFixedSizeDialogHint);//设置对话框固定大小
    int ret = dlgCAN->exec();  //显示界面
    if(ret == QDialog::Accepted) //如果确定
    {
        bool check1,check2;
        dlgCAN->getCANChose(check1,check2);
        int index = dlgCAN->getBpsIndex();
        int bps1 = bps[index]; // globe 获取对应波特率
        if(check1 == true)
        {
            QString name = dlgCAN->getCANName1();
            //把界面加载到下面
            addPageToTab(0,name,bps1);

        }
        if(check2 == true)
        {
            QString name = dlgCAN->getCANName2();
            //把界面加载到下面
            addPageToTab(1,name,bps1);

        }
        ui->actCAN_Open->setEnabled(false); //选择后功能隐藏

    }
    else {
 //      ui->tabWidget->clear();
         ui->actCAN_Open->setEnabled(true);
    }
}

void MainWindow::on_tabWidget_tabCloseRequested(int index)
{
    if(index < 0)
        return;

    QWidget* aForm=ui->tabWidget->widget(index);
    aForm->close();
    //这一句来判断当前是不是最后一个页面，是就删除，图标变亮
    if(ui->tabWidget->currentIndex() == 0)
    {
        ui->actCAN_Open->setEnabled(true);
    }

}

void MainWindow::on_actCAN_Close_All_triggered()
{
    ui->tabWidget->clear();
    ui->actCAN_Open->setEnabled(true); //清空后恢复功能
}

void MainWindow::on_tabWidget_customContextMenuRequested(const QPoint &pos)
{
    Q_UNUSED(pos)
    QMenu *menuList = new QMenu(this);
    //添加菜单项
//    menuList->addAction();
    menuList->addAction(ui->act_quit);
    menuList->exec(QCursor::pos()); //在当前光标下显示
    delete menuList;
}
